import UIKit
import WidgetKit

class ViewController: UIViewController {

    // 定义状态变量
    private var inputText: String = ""

    // 创建文本框
    private let textField: UITextField = {
        let tf = UITextField()
        tf.placeholder = "请输入内容..."
        tf.borderStyle = .roundedRect
        tf.translatesAutoresizingMaskIntoConstraints = false
        return tf
    }()

    // 创建按钮
    private let saveButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("保存", for: .normal)
        button.backgroundColor = .blue
        button.setTitleColor(.white, for: .normal)
        button.layer.cornerRadius = 15
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        
        // 添加子视图
        view.addSubview(textField)
        view.addSubview(saveButton)

        // 设置自动布局约束
        NSLayoutConstraint.activate([
            textField.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50),
            textField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            textField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            textField.heightAnchor.constraint(equalToConstant: 40),

            saveButton.topAnchor.constraint(equalTo: textField.bottomAnchor, constant: 20),
            saveButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            saveButton.widthAnchor.constraint(equalToConstant: 200),
            saveButton.heightAnchor.constraint(equalToConstant: 50)
        ])

        // 添加按钮点击事件
        saveButton.addTarget(self, action: #selector(didTapSaveButton), for: .touchUpInside)
        loadSavedText()
    }

    @objc private func didTapSaveButton() {
        // 获取文本框中的文本并保存到 UserDefaults
        if let text = textField.text, !text.isEmpty {
            let userDefaults = UserDefaults(suiteName: "group.com.netease.ma68")
            userDefaults?.set(text, forKey: "SavedText")
            userDefaults?.synchronize() // 确保数据立即写入磁盘
            
            print("保存的文本是: \(text)")
            // 隐藏键盘
            textField.resignFirstResponder()
            
            // 可选：向用户反馈保存成功
            let alert = UIAlertController(title: "保存成功", message: "您的输入已保存！", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "确定", style: .default, handler: nil))
            present(alert, animated: true, completion: nil)

                       
            WidgetCenter.shared.reloadTimelines(ofKind: "MyWidget")
        }
    }
    // 加载保存的文本到文本框
    private func loadSavedText() {
        let userDefaults = UserDefaults(suiteName: "group.com.netease.ma68")
        if let savedText = userDefaults?.string(forKey: "SavedText") {
            textField.text = savedText
            inputText = savedText
        }
    }
}

// 如果你需要直接展示这个视图控制器，可以在 AppDelegate 或者 SceneDelegate 中设置根视图控制器
